package access;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.charset.Charset;
import java.util.Arrays;

public class RandomAccessTest1 {

	public static void main(String[] args) throws IOException {
		
		File file = new File( "random-access.dat" ) ;
		final byte[] buffer = new byte[ 30 ]; // 数组默认值都是 0
		final Charset charset = Charset.forName( "UTF-8" );
		final byte defaultValue = 0 ;
		
		RandomAccessFile raf = new RandomAccessFile( file , "rw" ); // IOException
		
		// getFilePointer 可以获得 文件指针 ( 即指向文件中某个位置的索引值 )
		System.out.println( "file pointer : " + raf.getFilePointer() );
		
		// 将 file pointer 设置到参数对应的位置
		raf.seek( 72 );
		
		System.out.println( "file pointer : " + raf.getFilePointer() );
		
		// 从 当前位置 开始写入数据
		raf.writeInt( 9527 ); // 4 bytes : raf.getFilePointer() + 4 
		
		Arrays.fill( buffer ,  defaultValue );
		byte[] bytes = "华安".getBytes( charset );
		System.arraycopy( bytes , 0 ,  buffer , 0 , Math.min( buffer.length , bytes.length ) );
		// 从 当前位置 开始写入数据
		raf.write( buffer ); // 30 bytes : raf.getFilePointer() + 30 
		
		// 从 当前位置 开始写入数据
		raf.writeChar( '男' ); // 2 bytes : raf.getFilePointer() + 2
		
		System.out.println( "file pointer : " + raf.getFilePointer() );
		
		raf.seek( 36 ); // 将 file pointer 移动到 36 
		
		System.out.println( "file pointer : " + raf.getFilePointer() );
		
		raf.writeInt( 8526 ); // 4 bytes.
		
		Arrays.fill( buffer ,  defaultValue );
		bytes = "秋香".getBytes( charset );
		System.arraycopy( bytes , 0 ,  buffer , 0 , Math.min( buffer.length , bytes.length ) );
		raf.write( buffer ); // 30 bytes.
		
		raf.writeChar( '女' ); // 2 bytes 
		
		System.out.println( "file pointer : " + raf.getFilePointer() );
		
		
		raf.close();
	}

}
